import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import { tbactivityinformation } from '../../../atoms/db';

const logger = anylogger('pages/api/activity/editlaunch.api');


export type Result = {
	ok: boolean;
	message: string;
};


export type Message = ITbactivityinformation;

/**
 * 发起活动-编辑
 */
const handler = an48<Result>();

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const { aid, theme, ...body } = req.body as Message;
		//必填校验
		if (!aid) {
			res.status(200).json({ ok: false, message: '活动id不能为空' });
			return;
		}
		if (!theme) {
			res.status(200).json({ ok: false, message: '活动主题不能为空' });
			return;
		}
		//活动主题是否改变，改变需查重
		const d = await tbactivityinformation().first('aid').where({ aid }).andWhere({ theme });
		if (!d || !d.aid) {
			const d1 = await tbactivityinformation().first('aid').andWhere({ theme });
			if (d1 && d1.aid) {
				res.status(200).json({ ok: false, message: '活动主题不能重复' });
				return;
			}
		}
		await tbactivityinformation().update({
			theme,
			...body
		}).where({ aid });
		res.status(200).json({ ok: true, message: '' });
	} catch (error) {
		logger.error(error);
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
